N = 8 -- 棋盘大小

-- 检查(n,c)是否不会被攻击
function isPlaceOk(a, n, c)
    for i = 1, n - 2 do
        if(a[i] == c) or
        (a[i] - i == c - n) or
        (a[i] + i == c + n) then
            return false;
        end
    end
    return true;
end

-- 打印棋盘
function printSolution(a)
    for i = 1, N do -- 对于每一行
        for j = 1, N do -- 和每一列
            io.write(a[i] == j and "X" or "-", " ")
        end
        io.write("\n")
    end
    io.write("\n")
end

-- 把从'n'到'N'的所有皇后放在棋盘'a'上
function addQueue(a, n) 
    if n > N then
        printSolution(a)
    else
        for c = 1, N do
            if isPlaceOk(a, n, c) then
                a[n] = c
                addQueue(a, n + 1)    
            end
        end
    end
end
addQueue({},1)